package com.kintreda.ieco_server.core.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Service异常通知
 * Service耗時环绕通知
 */
@Component
@Aspect
public class ServiceAspect {
	
	protected static Logger logger = LoggerFactory.getLogger(ServiceAspect.class);

	private static final int CONSUMING_TIME = 3000;  
	
	private static final String SERVICE_ASPECT = "execution(* com.kintreda.ieco_server..service.impl.*.*(..))";

	public ServiceAspect() {
		
	}
	
	@AfterThrowing(value=SERVICE_ASPECT,throwing="ex")
    public void afterThrowing(JoinPoint joinPoint,Exception ex){
        Object object = joinPoint.getSignature();
        logger.error("Service 错误发生在:" + object + ",错误:" + ex);
    }
	
	
	@Around(SERVICE_ASPECT)  
    public Object timeAround(ProceedingJoinPoint joinPoint) {  
        // 定义返回对象、得到方法需要的参数  
        Object obj = null;  
        Object[] args = joinPoint.getArgs();  
        long startTime = System.currentTimeMillis();  
  
        try {  
            obj = joinPoint.proceed(args);  
        } catch (Throwable e) {  
            logger.error("统计某方法执行耗时环绕通知出错", e);  
        }  
  
        // 获取执行的方法名  
        long endTime = System.currentTimeMillis();  
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();  
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();  
  
        // 打印耗时的信息  
        long diffTime = endTime - startTime;  
        if (diffTime > CONSUMING_TIME) {  
            logger.warn("方法耗時警告:" + methodName + ",执行耗时：" + diffTime + " ms");  
        }  
        return obj;  
    }  
	
}
